package com.why.websocketmqttstudy.why.websocket.service;


import com.why.websocketmqttstudy.why.websocket.handler.ServerHeartBeat;
import com.why.websocketmqttstudy.why.websocket.handler.WebSocketHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * NettyServer Netty服务器配置
 * 
 * @author zhengkai.blog.csdn.net
 * @date 2019-06-12
 */
@Component
public class NettyServer {

	public void start(int port) throws Exception {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			ServerBootstrap sb = new ServerBootstrap();
			sb.option(ChannelOption.SO_BACKLOG, 1024);
			sb.group(group, bossGroup)
					.channel(NioServerSocketChannel.class)
					.localAddress(port)
					.childHandler(new ChannelInitializer<SocketChannel>() {                 
						@Override
						protected void initChannel(SocketChannel ch) throws Exception {

							System.out.println("收到新连接");
							ch.pipeline().addLast(new HttpServerCodec());
							ch.pipeline().addLast(new ChunkedWriteHandler());
							ch.pipeline().addLast(new HttpObjectAggregator(8192));
							ch.pipeline().addLast(new IdleStateHandler(60,0,0, TimeUnit.SECONDS));
							ch.pipeline().addLast(new ServerHeartBeat());
							//ch.pipeline().addLast(new AuthWebSocketHandler());
							
							//ch.pipeline().addLast(new WebSocketServerProtocolHandler("/poc_service", null, true, 65536 * 10));
							ch.pipeline().addLast(new WebSocketHandler());
						}
					});
			ChannelFuture cf = sb.bind().sync(); // 服务器异步创建绑定
			System.out.println(NettyServer.class + " 启动正在监听： " + cf.channel().localAddress());
			cf.channel().closeFuture().sync(); // 关闭服务器通道
		} finally {
			group.shutdownGracefully().sync(); // 释放线程池资源
			bossGroup.shutdownGracefully().sync();
		}
	}
}
